
class Excel:
    """
        Sub TestMacro1()
        '
        ' TestMacro1 宏
        ' 记录操作
        '

        '
            Columns("X:X").Select
            Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
            Range("X5").Select
            ActiveWindow.ScrollColumn = 3
            ActiveWindow.ScrollColumn = 2
            ActiveWindow.ScrollColumn = 1
            ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _
                "按学号排列\3120210256付嘉瑜.pdf", TextToDisplay:="按学号排列\3120210256付嘉瑜.pdf"
            ActiveWorkbook.Names("_3120210256.pdf").Comment = ""
            Range("X5").Select
            Selection.Hyperlinks(1).TextToDisplay = "3120210256付嘉瑜.pdf"
            Columns("X:X").ColumnWidth = 15.88
            Columns("X:X").ColumnWidth = 19.75
            Range("X6").Select
            Application.Goto Reference:="TestMacro1"
        End Sub
    """

    def __init__(self, visible=True):
        self.app  = gencache.EnsureDispatch('Excel.Application')
        self.app.Visible = visible

    @property
    def Workbook(self):
        return self.app.ActiveWorkbook

    def open(self, filename, readonly=True):
        _, ext = splitext(filename)
        assert(ext == '.xlsx' or ext == '.xls')
        self.app.Workbooks.Open(filename, ReadOnly=readonly)
        return self.Workbook

    def area(self, address:str):
        return self.app.Range(address).GetValue()

    def addLink(self, address, text=None, anchor=None):
        if text is None:
            text = address
        if anchor is None:
            anchor = self.app.Selection
        anchor = self.app.Range(anchor)
        return self.app.ActiveSheet.Hyperlinks.Add(Anchor=anchor, Address=address, TextToDisplay=text)

    def __del__(self):
        self.app.Quit()

